package com.nl.countdownclock.client;
import java.util.Date;
import java.lang.IllegalArgumentException;

import com.google.gwt.i18n.client.DateTimeFormat;

public class Clock {
	long target;
	boolean isCountdown;
	final String IO2011 = "2011.05.10,09:00-700";  // Google I/O 2011 begins May 10, 2011 9am PDT
	
	public Clock(  boolean isCountdown, long millisTarget ){
		init(isCountdown, millisTarget);
	}
	public Clock(boolean isCountdown, String targetTimeSpec ) {
		init(isCountdown, targetTimeSpec);
	}	
	public Clock(boolean isCountdown, Date targetDate ) {
		init(isCountdown, targetDate.getTime());
	}	
	public Clock(boolean isCountdown){
		long target;
		if(isCountdown)
			init(isCountdown);
		else
			init(isCountdown, millisNow() );
	}
	public Clock(){
		init(true);
		}
	
	public void init(boolean isCountdown, String targetTimeSpec){
		long targetMillis;
		
		Date targetDate = parseTime(targetTimeSpec);
		targetMillis = targetDate.getTime();
		init(isCountdown, targetMillis);
	}
	
	public void init(boolean isCountdown) {
		if (isCountdown)
				init(isCountdown, IO2011);
		else
			init(isCountdown, millisNow());
	}
	
	public void init(boolean isCountdown, long targetTime){
		this.isCountdown = isCountdown;
		this.target = targetTime;
	}
	
	
	public void setCountdown(boolean isCountdown){
		this.isCountdown = isCountdown;
	}
	
	public long getMillisDiff(){
		if(isCountdown)
			return target - millisNow();
		else
			return millisNow() - target;
	}
	
	public boolean isNegative(){  // will happen when countdown time is reached
		return isCountdown && (millisNow() > target);
	}

	public int[] getDigits(){
		// take absolute value so that if time has passed, it becomes an overdue counter
		long diff = Math.abs(getMillisDiff())/1000;
		int seconds = (int)(diff % 60);
		diff = diff/60;
		int  minutes = (int)(diff % 60);
		diff = diff/60;
		int hours = (int)(diff % 24);
		int days = (int)diff/24;
		int digits[] = new int[9];
		
		// days
		digits[0] = days/100;
		digits[1] = (days/10) % 10;
		digits[2] = days % 10;
		
		// hours
		digits[3] = hours / 10;
		digits[4] = hours % 10;
		// minutes
		digits[5] = minutes / 10;
		digits[6] = minutes % 10;
		//seconds
		digits[7] = seconds / 10;
		digits[8] = seconds % 10;
		
		
		// return an array[0-8] of digits for each in the form:
		// DDDHHMMSS
		return digits;
		}
	public String formatDigits(){
		int[] n = getDigits();
		// return a string in the form DDD:HH:MM:SS
		return "" + n[0] + n[1]+ n[2] + ':'+n[3]+n[4]+':'+n[5]+n[6]+':'+n[7]+n[8];
	}

	static public long millisNow(){
		Date now = new Date();
		return now.getTime();
	}
	
	static public Date parseTime(String timespec){
		DateTimeFormat pt = DateTimeFormat.getFormat("yyyyy.MM.dd,hh:mmZ");
		
		Date targetDate = pt.parse(timespec);
		return targetDate;

	}

}
